﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.SessionState;
using System.Web.Script.Serialization;
using System.Linq.Expressions;
using System.Data;


namespace HQWeb.View
{
    /// <summary>
    /// 文件通过查询返回查询符合要求的文件
    /// </summary>
    public class GetFile : IHttpHandler, IReadOnlySessionState
    {
        private string projecttype = "";
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            if (context.Session["BRANCH_ID"] != null)
            {
                Dictionary<string, string> dW = JsonDeserialize(context.Request.Form["Where"].ToString());
                //if (dW.ContainsKey("projectid"))
                //{
                //    JavaScriptSerializer js = new JavaScriptSerializer();
                //    context.Response.Write(js.Serialize(BindProjectView(dW["projectid"])));
                //}
                //else
                //{
                string strType = context.Request["type"];
                int strNum = Convert.ToInt32(context.Request["num"]);
                if (strType != "6")                              //是否是主题婚礼获取数据
                {
                    string strBranchID = context.Session["BRANCH_ID"].ToString();
                    projecttype = context.Request["projecttype"];      //所属模块
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    context.Response.Write(js.Serialize(BindView(strType, strNum, strBranchID, dW)));
                }
                else
                {
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    context.Response.Write(js.Serialize(BindThemView(strNum, context.Session["BRANCH_ID"].ToString(), dW)));
                }
                //   }
            }
            else
            {
                context.Response.Write("SessionTimeout");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string[] BindProjectView(string strProject)
        {
            string[] strarry = new string[3];
            BLL.Progect.T_PUB_FILE fileBll = new BLL.Progect.T_PUB_FILE();
            IEnumerable<Model.Progect.T_PUB_FILE> listModle = fileBll.GetProjectFile(strProject);
            listModle = listModle.OrderByDescending(p => p.SETTOPTIME);
            int intCoount = listModle.Count();
            strarry[0] = intCoount.ToString();
            StringBuilder strHtml = new StringBuilder();
            Model.Progect.T_PUB_FILE model;
            string strPhotoUrl = "";             //图片地址
            int PhototoIndex = 0; ;
            for (int i = 0; i < intCoount; i++)
            {
                model = listModle.ElementAt(i);
                strHtml.Append("<li class=\"list\" onmousemove='mson(this)' onmouseout='msout(this)'>");
                strHtml.Append("<div class=\"p-img\">");
                if (model.TYPE == "0")               //图片
                {
                    strHtml.Append("<a target=\"_blank\" onclick=\"GetView(" + PhototoIndex + ",'','')\">");
                    PhototoIndex = PhototoIndex + 1;
                    strPhotoUrl = strPhotoUrl + model.URLOriginal + ",";
                    strHtml.Append(" <img onerror=\"this.src='http://www.360buy.com/images/none/none_150.gif'\" ");
                    strHtml.Append(string.Format("alt=\"{0}\"", model.FILE_NAME));
                    strHtml.Append(string.Format("width=\"280px\" height=\"150px\" src=\"../{0}\"></a>", model.URLThumbnail.Replace("//", "/")));
                }
                else
                {
                    strHtml.Append("<a target=\"_blank\" onclick=\"GetView(-1,'" + model.URLOriginal.Replace("//", "/") + "','" + model.URLThumbnail.Replace("//", "/") + "')\">");
                    strHtml.Append(" <img onerror=\"this.src='http://www.360buy.com/images/none/none_150.gif'\" ");
                    strHtml.Append(string.Format("alt=\"{0}\"", model.FILE_NAME));
                    strHtml.Append(string.Format("width=\"280px\" height=\"150px\" src=\"../{0}\"></a>", model.URLThumbnail.Replace("//", "/")));
                }
                strHtml.Append("<div class=\"pi7\">");
                strHtml.Append(" </div>");
                strHtml.Append("</div>");
                strHtml.Append("<div class=\"p-name\">");
                strHtml.Append("<font ");
                strHtml.Append("class=\"adwords\" name=\"577394\">" + model.FILE_TITEL + "</font></div>");
                strHtml.Append("</li>");
            }

            strarry[1] = strHtml.ToString();
            if (strPhotoUrl != "")
            {
                strarry[2] = strPhotoUrl.Trim(',');
            }
            return strarry;

        }
        //绑定数据
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strType"></param>
        /// <param name="NUM"></param>
        /// <param name="strBranchID"></param>
        /// <param name="dW"></param>
        /// <returns></returns>
        private string[] BindView(string strType, int NUM, string strBranchID, Dictionary<string, string> dW)
        {
            string[] strarry = new string[3];
            IEnumerable<Model.View.Exhibition> listModle = Universal.Caches.getCaceData(strBranchID.ToString());
            listModle = listModle.OrderByDescending(p => p.SETTOPTIME);
            IEnumerable<Model.View.Exhibition> resloutList;

            if (dW.Count == 0)
            {
                if (strType == "1") //订制模块显示包含所属模块为空
                {
                    resloutList = from n in listModle where(n.FILE_FORM.Contains(strType + ",") || n.FILE_FORM == "" || n.FILE_FORM == null) select n;
                }
                else
                {
                    resloutList = from n in listModle where n.FILE_FORM.Contains(strType + ",") select n;
                }
            }
            else
            {
                Expression<Func<Model.View.Exhibition, bool>> expr = n => GetCondition(n, dW);
                var _query = listModle.Where<Model.View.Exhibition>(expr.Compile());
                if (strType == "1") //订制模块显示包含所属模块为空
                {
                    resloutList = from n in _query where  (n.FILE_FORM.Contains(strType + ",")|| n.FILE_FORM == "" || n.FILE_FORM == null) select n;
                }
                else
                {
                    resloutList = from n in _query where n.FILE_FORM.Contains(strType + ",") select n;
                }

            }
            //resloutList.OrderByDescending(p => p.SETTOPTIME);
            int intCoount = resloutList.Count();
            strarry[0] = intCoount.ToString();
            IEnumerable<Model.View.Exhibition> resloutLists;
            resloutLists = resloutList.Skip((NUM - 1) * 16).Take(16);
            //resloutLists.OrderByDescending(p => p.SETTOPTIME);
            intCoount = resloutLists.Count();
            intCoount = intCoount < 16 ? intCoount : 16;
            StringBuilder strHtml = new StringBuilder();
            Model.View.Exhibition model;
            string strPhotoUrl = "";             //图片地址
            int PhototoIndex = 0; ;
            for (int i = 0; i < intCoount; i++)
            {
                model = resloutLists.ElementAt(i);
                strHtml.Append("<li class=\"list\" onmousemove='mson(this)' onmouseout='msout(this)'>");
                strHtml.Append("<div class=\"p-img\">");
                if (model.TYPE == "0")               //图片
                {
                    strHtml.Append("<a target=\"_blank\" onclick=\"GetView(" + PhototoIndex + ",'','')\">");
                    PhototoIndex = PhototoIndex + 1;
                    strPhotoUrl = strPhotoUrl + model.URLOriginal + ",";
                    strHtml.Append(" <img onerror=\"this.src='http://www.360buy.com/images/none/none_150.gif'\" ");
                    strHtml.Append(string.Format("alt=\"{0}\"", model.FILE_NAME));
                    strHtml.Append(string.Format("width=\"280px\" height=\"150px\" src=\"../{0}\"></a>", model.URLThumbnail.Replace("//", "/")));
                }
                else
                {
                    strHtml.Append("<a target=\"_blank\" onclick=\"GetView(-1,'" + model.URLOriginal.Replace("//", "/") + "','" + model.URLThumbnail.Replace("//", "/") + "')\">");
                    strHtml.Append(" <img onerror=\"this.src='http://www.360buy.com/images/none/none_150.gif'\" ");
                    strHtml.Append(string.Format("alt=\"{0}\"", model.FILE_NAME));
                    strHtml.Append(string.Format("width=\"280px\" height=\"150px\" src=\"../{0}\"></a>", model.URLThumbnail.Replace("//", "/")));
                }
                strHtml.Append("<div class=\"pi7\">");
                strHtml.Append(" </div>");
                strHtml.Append("</div>");
                strHtml.Append("<div class=\"p-name\">");
                strHtml.Append("<font ");
                strHtml.Append("class=\"adwords\" name=\"577394\">" + model.FILE_TITEL + "</font></div>");
                strHtml.Append("</li>");
            }

            strarry[1] = strHtml.ToString();
            if (strPhotoUrl != "")
            {
                strarry[2] = strPhotoUrl.Trim(',');
            }
            return strarry;

        }

        /// <summary>
        /// 根据查询条件过滤
        /// </summary>
        /// <param name="_Table"></param>
        /// <param name="dW"></param>
        /// <returns></returns>
        private bool GetCondition(Model.View.Exhibition _Table, Dictionary<string, string> dW)
        {

            bool _result = true;
            int intTemp;
            foreach (KeyValuePair<string, string> item in dW)
            {
                switch (item.Key)
                {
                    case "dress_type":
                        _result &= _Table.DRESS_TYPE.Contains(item.Value);
                        break;
                    case "dress_level":
                        _result &= _Table.DRESS_LEVEL.Contains(item.Value);
                        break;
                    case "dress_color":
                        _result &= _Table.DRESS_COLOR.Contains(item.Value);
                        break;
                    case "dress_price":
                        _result &= _Table.DRESS_PRICE.Contains(item.Value);
                        break;
                    case "wedding_color":
                        _result &= _Table.WEDDING_COLOR.Contains(item.Value);
                        break;
                    case "wedding_price":
                        _result &= _Table.WEDDING_PRICE.Contains(item.Value);
                        break;
                    case "wedding_month":
                        _result &= _Table.WEDDING_MONTH.Contains(item.Value);
                        break;
                    case "wedding_style":
                        _result &= _Table.WEDDING_STYLE.Contains(item.Value);
                        break;
                    case "material":
                        _result &= _Table.MATERIAL_STAR.Contains(item.Value);
                        break;
                    case "celebration_type":
                        _result &= _Table.CELEBRATION_TYPE.Contains(item.Value);
                        break;
                    case "max_price":
                        int.TryParse(item.Value, out intTemp);
                        _result &= _Table.MAX_PRICE >= intTemp;
                        break;
                    case "min_price":
                        int.TryParse(item.Value, out intTemp);
                        _result &= _Table.MIN_PRICE <= intTemp;
                        break;
                    case "project_type":
                        _result &= _Table.PROJECT_TYPE.Contains(item.Value);
                        break;
                    case "area":
                        _result &= _Table.AREA.Contains(item.Value);
                        break;
                    case "newschool":
                        _result &= _Table.NEWSCHOOL.Contains(item.Value);
                        break;
                    case "hotel_name":
                        _result &= _Table.HOTEL_NAME.Contains(item.Value);
                        break;
                    case "hotel_desk_num":
                        _result &= _Table.HOTEL_DESK_NUM.Contains(item.Value);
                        break;
                    case "hotel_style":
                        _result &= _Table.HOTEL_STYLE.Contains(item.Value);
                        break;
                    case "hotel_specification":
                        _result &= _Table.HOTEL_SPECIFICATION.Contains(item.Value);
                        break;
                    case "color":
                        _result &= _Table.COLOR.Contains(item.Value);
                        break;
                    case "style":
                        _result &= _Table.STYLE.Contains(item.Value);
                        break;
                    case "material_star":
                        _result &= _Table.MATERIAL_STAR.Contains(item.Value);
                        break;
                    case "isnull":
                        _result &= _Table.ISFLAG==false;
                        break;
                    case "filename":
                        _result &= _Table.FILE_TITEL.Contains(item.Value);
                        break;
                    default:
                        _result &= true;
                        break;
                }
                if (projecttype != "")
                {
                    _result &= _Table.PROJECT_TYPE.Contains(projecttype);
                }
            }
            return _result;
        }

        /// <summary>
        /// 用于主题婚礼界面绑定数据
        /// </summary>
        /// <param name="NUM">当前页</param>
        /// <param name="strBranchID">店ID</param>
        /// <param name="dW">查询条件</param>
        /// <returns></returns>
        private string[] BindThemView(int NUM, string strBranchID, Dictionary<string, string> dW)
        {
            string[] strarry = new string[3];
            #region 获得查询条件

            string strWEDDING_COLOR = "";
            string strWEDDING_PRICE = "";
            string strWEDDING_MONTH = "";
            string strWEDDING_STYLE = "";
            string strHOTEL_NAME = "";
            string strType = "";
            foreach (KeyValuePair<string, string> item in dW)
            {
                switch (item.Key)
                {
                    case "color":
                        strWEDDING_COLOR = item.Value;
                        break;
                    case "wedding_price":
                        strWEDDING_PRICE = item.Value;
                        break;
                    case "wedding_month":
                        strWEDDING_MONTH = item.Value;
                        break;
                    case "style":
                        strWEDDING_STYLE = item.Value + ",";
                        break;
                    case "hotel_name":
                        strHOTEL_NAME = item.Value;
                        break;
                    case "celebration_type":
                        strType = item.Value;
                        break;
                    default:
                        break;
                }
            }

            #endregion

            //得到主题婚礼和文件
            DataTable dt = GetThemFile(strBranchID, strWEDDING_COLOR, strWEDDING_PRICE, strWEDDING_MONTH, strWEDDING_STYLE, strHOTEL_NAME, strType);

            //翻页处理
            int intCoount = dt.Rows.Count;
            strarry[0] = intCoount.ToString();
            int index = intCoount > NUM * 16 ? NUM * 16 : intCoount;
            int begin = (NUM - 1) * 16;
            StringBuilder strHtml = new StringBuilder();
            DataRow rowTemp;
            string strTitle;
            for (int i = begin; i < index; i++)
            {
                rowTemp = dt.Rows[i];
                strTitle = rowTemp["title"].ToString();
                strHtml.Append("<li class=\"list\" onmousemove='mson(this)' onmouseout='msout(this)'>");
                strHtml.Append("<div class=\"p-img\">");

                strHtml.Append(string.Format("<a target=\"_blank\" onclick=\"ShowTeme('{0}','{1}','{2}','{3}')\">", strTitle, rowTemp["purl"], rowTemp["vurl"], rowTemp["id"]));
                strHtml.Append(" <img onerror=\"this.src='http://www.360buy.com/images/none/none_150.gif'\" ");
                strHtml.Append(string.Format("alt=\"{0}\"", strTitle));
                strHtml.Append(string.Format("width=\"280px\" height=\"150px\" src=\"../{0}\"></a>", rowTemp["surl"]));

                strHtml.Append("<div class=\"pi7\">");
                strHtml.Append(" </div>");
                strHtml.Append("</div>");
                strHtml.Append("<div class=\"p-name\">");
                strHtml.Append(" <a href=\"\" target=\"_blank\">" + strTitle + "<font style=\"color: #ff0000\"");
                strHtml.Append("class=\"adwords\" name=\"577394\"></font></a></div>");
                strHtml.Append("</li>");
            }
            strarry[1] = strHtml.ToString();
            strarry[2] = "";
            return strarry;
        }

        /// <summary>
        /// 根据条件获得主题婚礼文件
        /// </summary>
        /// <param name="strBRANCH_ID">分店ID</param>
        /// <param name="strWEDDING_COLOR">婚礼色彩</param>
        /// <param name="strWEDDING_PRICE">价格</param>
        /// <param name="strWEDDING_MONTH">月份</param>
        /// <param name="strWEDDING_STYLE">风格</param>
        /// <param name="strHOTEL_NAME">酒店名称</param>
        /// <param name="strTypes"></param>
        /// <returns></returns>
        private DataTable GetThemFile(string strBRANCH_ID, string strWEDDING_COLOR, string strWEDDING_PRICE, string strWEDDING_MONTH, string strWEDDING_STYLE, string strHOTEL_NAME, string strTypes)
        {

            BLL.SysManage.T_PUB_WEDDINGTHEME themeBll = new BLL.SysManage.T_PUB_WEDDINGTHEME();
            DataTable dt = themeBll.GetThemmFile(strBRANCH_ID, strWEDDING_COLOR, strWEDDING_PRICE, strWEDDING_MONTH, strWEDDING_STYLE, strHOTEL_NAME, strTypes);//获取符合条件的所有主题婚礼文件
            DataTable newTable = new DataTable();                  //新datatable保存查询结果
            newTable.Columns.Add("id", typeof(string));            //主题婚礼ID
            newTable.Columns.Add("title", typeof(string));         //主题婚礼标题
            newTable.Columns.Add("surl", typeof(string));          //缩略图地址
            newTable.Columns.Add("purl", typeof(string));          //图片地址
            newTable.Columns.Add("vurl", typeof(string));          //视频地址
            int coutn = dt.Rows.Count;
            DataRow rowTemp;
            DataRow[] findRow;
            string strid;
            string strType;
            string strURLOriginal;
            string strURLThumbnail;
            for (int i = 0; i < coutn; i++)
            {
                rowTemp = dt.Rows[i];
                strid = rowTemp["ID"].ToString();
                strType = rowTemp["TYPE"].ToString();
                strURLOriginal = rowTemp["URLOriginal"].ToString().Replace("//", "/");
                strURLThumbnail = rowTemp["URLThumbnail"].ToString().Replace("//", "/");
                findRow = newTable.Select(string.Format(" id='{0}'", strid));        //查询结果中是否存在该主题婚礼
                if (findRow.Length > 0)                 //已经存在就追加
                {
                    if (strType == "0")     //图片
                    {
                        findRow[0]["purl"] = findRow[0]["purl"] + strURLOriginal + ",";   //图片地址
                        findRow[0]["surl"] = strURLThumbnail;                             //缩率图地址用最后一个
                    }
                    else
                    {
                        findRow[0]["vurl"] = strURLOriginal;                              //视频只能存在一个
                    }

                }
                else                                                                     //不存在就在查询结果中追加一行
                {
                    DataRow newRows = newTable.NewRow();
                    newRows["id"] = strid;                                                //主题婚礼ID
                    //newRows["title"] = rowTemp["TITLE"];
                    newRows["title"] = rowTemp["TITLE"];                                  //标题
                    if (strType == "0")     //图片                      
                    {
                        newRows["purl"] = strURLOriginal + ",";
                        newRows["surl"] = strURLThumbnail;
                    }
                    else
                    {
                        newRows["vurl"] = strURLOriginal;
                    }
                    newTable.Rows.Add(newRows);
                }
            }
            return newTable;
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        public Dictionary<string, string> JsonDeserialize(string jsonString)
        {
            Dictionary<string, string> obj = new Dictionary<string, string>();
            int index;
            string strKey;
            string strValue;
            string[] strArr = jsonString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string item in strArr)
            {
                index = item.IndexOf('|');
                strKey = item.Substring(0, index);
                strValue = item.Substring(index + 1);
                obj.Add(strKey.ToLower(), strValue);
            }
            return obj;
        }

    }
}